package cn.tedu.egcar2.controller;

import cn.tedu.egcar2.base.response.JsonResult;
import cn.tedu.egcar2.base.response.StatusCode;
import cn.tedu.egcar2.mapper.UserMapper;
import cn.tedu.egcar2.pojo.dto.UserLoginParam;
import cn.tedu.egcar2.pojo.dto.UserRegParam;
import cn.tedu.egcar2.pojo.entity.User;
import cn.tedu.egcar2.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/user/")
@Slf4j
@Api(tags = "01.用户管理模块")
public class UserController {
    @Autowired
    public UserMapper userMapper;

    @PostMapping("reg")
    @ApiOperation("注册功能")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@RequestBody UserRegParam userRegParam ){
        log.debug("userRegParam={}",userRegParam);

        String username = userRegParam.getUsername();
        int num = userMapper.selectByUsername(username);
        if(num == 0){
            User user = new User();
            BeanUtils.copyProperties(userRegParam,user);
            user.setId(1L);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());

            log.debug("user={}",user);

            userMapper.insertUser(user);
            return JsonResult.success(StatusCode.OPERATION_SUCCESS);
        }else {
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
    }

    @PostMapping("login")
    @ApiOperation("登录功能")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam,
                            @ApiIgnore HttpSession session){
        log.debug("userLoginParam={}",userLoginParam);

        String username = userLoginParam.getUsername();
        String password = userLoginParam.getPassword();

        UserVO userVO = userMapper.selectByUsernameAndPassword(username, password);

        if(userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }

        session.setAttribute("user",userVO);
        return JsonResult.success(userVO);
    }
}
